package com.xkdx.guangguang.fragment.my.setup;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.xkdx.caipiao.R;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.my.pay.TCPSocketCallback;
import com.xkdx.guangguang.fragment.my.pay.TCPSocketConnect;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.util.DialogFactory;
import com.xkdx.guangguang.util.SharePrefenceUtil;

public class SetUpPosQueryFragment extends BaseFragment implements
		OnClickListener, TCPSocketCallback {

	private View view;
	private Button back, im_query;
	private EditText ed_price, ed_trace;

	private SharePrefenceUtil sp;
	private String price, trace;
	private Dialog dialog;
	private String pos_trace;
	private TCPSocketConnect connect = null;
	private String ip;
	private String newTrace;
	private String posResultGetQuery;
	private static final String TYPE_QUERY = "QUERY";

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sp = new SharePrefenceUtil(getActivity(), IConstants.SP_POS);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.pos_query, container, false);
		findViews(view);
		return view;
	}

	private void findViews(View view) {
		ed_price = (EditText) view.findViewById(R.id.ed_pos_query_price);
		ed_trace = (EditText) view.findViewById(R.id.ed_pos_trace);
		im_query = (Button) view.findViewById(R.id.im_pos_trace_query);
		back = (Button) view.findViewById(R.id.ed_posquery_back);
		im_query.setOnClickListener(this);
		back.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ed_posquery_back: // 返回按钮

			FragmentManager fm = getFragmentManager();
			fm.popBackStack();
			break;

		case R.id.im_pos_trace_query: // 提交验证码和新密码(重置密码 )
			price = ed_price.getText().toString().trim();
			trace = ed_trace.getText().toString().trim();
			if (!isPoaTraceAvilidate()) {
				return;
			} else {
				SendPosQuery(price, trace); // 订单查询
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 订单查询
	 */
	private void SendPosQuery(String price, String trace) {
		dialog = DialogFactory.creatRequestDialog(getActivity(),
				"正在查询订单信息,请耐心等待...");
		dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
		dialog.show();
		pos_trace = sp.getPosTrace();
		ip = sp.getPosIP();

		String traceStr = pos_trace.substring(12);
		int lastSixnum = Integer.parseInt(traceStr);
		lastSixnum = lastSixnum + 1;
		String tracelastSixNum = String.format("%06d", lastSixnum);
		String mac_address = sp.getPosMac();
		newTrace = mac_address + tracelastSixNum;

		PosRequest();

	}

	/**
	 * pos机支付
	 */
	private void PosRequest() {
		connect = new TCPSocketConnect(this);

		connect.setAddress(ip, IConstants.POS_PORT);
		new Thread(connect).start();

	}

	/**
	 * 判断提交按钮相关是否合法
	 * 
	 * @return true合法 , false不合法
	 */
	private boolean isPoaTraceAvilidate() {

		if (TextUtils.isEmpty(price)) {
			ed_price.setFocusable(true);
			ed_price.setFocusableInTouchMode(true);
			ed_price.requestFocus();
			Toast.makeText(getActivity(), "金额不能为空...", Toast.LENGTH_SHORT)
					.show();
			return false;
		} else if (TextUtils.isEmpty(trace)) {
			ed_trace.setFocusable(true);
			ed_trace.setFocusableInTouchMode(true);
			ed_trace.requestFocus();
			Toast.makeText(getActivity(), "原流水号不能为空...", Toast.LENGTH_SHORT)
					.show();
			return false;

		}
		return true;
	}

	@Override
	public void findView() {
	}

	@Override
	public void setOnClick() {
	}

	@Override
	public void showLoading() {
	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {
	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
	}

	@Override
	public void tcp_connected() {
		handler.sendEmptyMessage(1);
	}

	@Override
	public void tcp_receive(String result) {
		try {

			posResultGetQuery = result;

		} catch (Exception e) {
			e.printStackTrace();
		}
		handler.sendEmptyMessage(2);
	}

	@Override
	public void tcp_disconnect() {
		handler.sendEmptyMessage(3);
	}

	@Override
	public void tcp_closeconnect() {
		handler.sendEmptyMessage(4);
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 1:
				Toast.makeText(getActivity(), "连接成功!", 0).show();
				String queryMacStr = sendRequest(TYPE_QUERY); // 对应消息体
				int qmLength = queryMacStr.length();
				String headqmMessage = IConstants.TentoSixteen(qmLength); // 对应消息头
				byte[] head_byte = new byte[2]; // 对应消息头字节数 固定为2
				head_byte = IConstants.hexStringToBytes(headqmMessage);

				connect.write(head_byte); // 发送
				connect.writeBody(queryMacStr);

				break;
			case 2:
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}

				/**
				 * 解析返回数据
				 */
				JsonQueryParse(posResultGetQuery);

				break; 

			case 3:
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}

				Toast.makeText(getActivity(), "pos连接失败，请检查网络连接,重新获取mac地址!", 0)
						.show();

				break;

			case 4:
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}
				Log.i("pay", "关闭连接");
				break;
			}
		}
	};

	protected String sendRequest(String type) {
		String mainBody = new String();

		String amt = price;
		String oldtrace = trace;

		mainBody = CreateQueryRequest("QUERY", amt, newTrace, oldtrace);

		return mainBody.toString();
	}

	protected void JsonQueryParse(String resultShow2) {
		JSONObject obj;
		try {

			int pos = resultShow2.indexOf("{");
			resultShow2 = resultShow2.substring(pos);
			obj = new JSONObject(resultShow2);

			String code = obj.getString("rescode");
			if (!(code.equals("00"))) {
				Toast.makeText(getActivity(), "订单查询失败，请重新获取", 0).show();

			} else {
				sp.setPosTrace(newTrace); // 保存流水号
				Toast.makeText(getActivity(), "订单查询成功", 0).show();

			}
		} catch (JSONException e) {
			Toast.makeText(getActivity(), "订单查询失败，请重新获取", 0).show();
		}
	}

	/**
	 * 查询接口
	 * 
	 * @param type
	 *            "Query"
	 * @param amt
	 *            总价格
	 * @param trace
	 *            流水号
	 * @param oldtrace
	 *            原流水号
	 */
	private String CreateQueryRequest(String type, String amt, String trace,
			String oldtrace) {

		StringBuffer sbuff = new StringBuffer();
		sbuff.append("{\"cmd\":\"");
		sbuff.append(type).append("\",\"amt\":\"").append(amt)
				.append("\",\"trace\":\"").append(trace)
				.append("\",\"oldtrace\":\"").append(oldtrace);
		sbuff.append("\"}");
		return sbuff.toString();

	}

}
